package com.sunb2b.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;

import com.sunb2b.util.WebUtils;

public class EntitlementFilter implements Filter{
	private Logger logger = Logger.getLogger(EntitlementFilter.class);//LogFactory.getLog(EntitlementFilter.class);
	// the WebApplicationContext will be used to get components for further check.
	private WebApplicationContext ctx;
	public void destroy() {
		this.ctx = null;
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		String ctxPath = session.getServletContext().getContextPath();
		String uri = request.getRequestURI().split(ctxPath)[1];
		String address = request.getRemoteAddr();
		if(!(uri.startsWith("/resources")||uri.startsWith("/upload")||uri.startsWith("/products"))){
			logger.info(address + " : " + uri);
			boolean isAdmin = WebUtils.isAdmin(request);
			boolean isMember = WebUtils.isMember(request);
			if(uri.startsWith("/member")){
				if(isMember){
					chain.doFilter(request, response);
					return;
				}
				else{
					response.sendRedirect(ctxPath + "/login");
					return;
				}
			}
			
			else if(uri.startsWith("/admin")){
				if(isAdmin||uri.startsWith("/admin/login")||uri.startsWith("admin/validate")){
					chain.doFilter(request, response);
					return;
				}
				else{
					response.sendError(403);
					return;
				}
			}
			else if(uri.startsWith("/product")&&(isAdmin||isMember)){
				chain.doFilter(request, response);
				return;
			}
		}
		chain.doFilter(request, response);
		return;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext sc = filterConfig.getServletContext();
		String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
		WebApplicationContext ctx = (WebApplicationContext) sc.getAttribute(key);
		this.ctx = ctx;
	}

}
